var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../db.js')
var md5 = require('md5-nodejs')
var multer = require('multer');
var router = express.Router()


// 新增评论
router.post('/saveContent', urlencodedParser, async function (req, res) {
    let { content, uid, bdid } = req.body
    let sql = `insert into discuss (content,uid,bdid) values (?,?,?)`

    let { data } = await db.doSQL(sql, [content, uid, bdid])
    if (!data.affectedRows) {
        res.send(db.handleError(data))
    } else {
        res.send(db.handleResults(data))
    }
})

// 搜索评论
router.get('/get-comment', async function (req, res) {
    let { bdid } = req.query
    let sql = `select d.content,d.t,u.name from discuss as d,users as u where u.id=d.uid && bdid=${bdid} order by d.id desc`
    let sql_count = `select count(*) as total from discuss where bdid=${bdid}`
    let { data } = await db.doSQL(sql)
    let r = await db.doSQL(sql_count)
    res.send(db.handleResults(data, r.data[0].total))
})

// 获取详情数据
router.get('/get-item', async function (req, res) {
    let { id } = req.query
    let sql = `select * from msbd where id=${id}`
    let { data } = await db.doSQL(sql)
    res.send(db.handleResults(data[0]))
})

// 是否点赞
router.get('/get-islikes-id', async function (req, res) {
    let { bdid, uid } = req.query
    let sql = `select * from likes where bdid=${bdid} && uid=${uid}`
    let { data } = await db.doSQL(sql)
    res.send(db.handleResults(data))
})

// 获取点赞条数
router.get('/get-likes-count', async function (req, res) {
    let { bdid } = req.query
    let sql = `select count(*) as total from likes where bdid=${bdid}`
    let { data } = await db.doSQL(sql)
    res.send(db.handleResults(data[0]))
})

// 取消点赞
router.get('/delete-dianzan', async function (req, res) {
    let { id } = req.query
    console.log(id);
    let sql = `delete from likes where id=${id}`
    let { data } = await db.doSQL(sql)
    res.send(db.handleResults(data[0]))
})


// 点赞(新增)
router.post('/dianzan', urlencodedParser, async function (req, res) {
    let { uid, bdid } = req.body
    let sql = `insert into likes (uid,bdid) values ("${uid}","${bdid}");`
    let { data } = await db.doSQL(sql)
    res.send(db.handleResults(data))
})

// 已读宝典（新增）
router.post('/save-study-bdid', urlencodedParser, async function (req, res) {
    let { uid, bdid } = req.body
    let sql = `insert into study (uid,bdid) values ("${uid}","${bdid}");`
    let { data } = await db.doSQL(sql)
    res.send(db.handleResults(data))
})








module.exports = router;